import os
from flask import Blueprint, jsonify, request, current_app
from app.server.ensemble_model import TemperatureForecaster
import traceback

evaluate_ensemble_bp = Blueprint('evaluate_ensemble', __name__)

@evaluate_ensemble_bp.route('/evaluate_ensemble', methods=['GET'])
def ensemble_evaluate():
    try:
        # 获取请求参数
        target_col = request.args.get('target', default='guilin_max', type=str)
        test_days = request.args.get('test_days', default=365, type=int)
        model_type = request.args.get('model_type', default='single', type=str)  # multi或single

        # 参数校验
        if model_type not in ['multi', 'single']:
            return jsonify({
                'status': 'error',
                'message': 'model_type参数必须为multi或single'
            }), 400

        forecaster = TemperatureForecaster(target_col=target_col)

        # 根据参数选择评估方法
        if model_type == 'multi':
            result = forecaster.evaluate_multi_model(test_days=test_days)
        else:
            result = forecaster.evaluate_single_model(test_days=test_days)

        if result['status'] == 'error':
            return jsonify({
                'status': 'error',
                'message': result['message']
            }), 400

        # 确保plot_path存在
        if 'plot_path' not in result:
            return jsonify({
                'status': 'error',
                'message': '评估结果中缺少图表路径'
            }), 500

        return jsonify({
            'status': 'success',
            'metrics': result['metrics'],
            'plot_url': f'/static/evaluation_plots/{os.path.basename(result["plot_path"])}',
            'model_type': 'Ensemble'  # 返回使用的模型类型
        })

    except Exception as e:
        current_app.logger.error(f"API错误: {traceback.format_exc()}")
        return jsonify({
            'status': 'error',
            'message': '内部服务器错误'
        }), 500


